"""
__author__ = '霍格沃兹测试开发学社'
__desc__ = '更多测试开发技术探讨，请访问：https://ceshiren.com/t/topic/15860'
"""
from flask import request
from flask_restx import Resource, Namespace, fields

from do.plan_do import PlanDo
from do.testcase_do import TestcaseDo
from server import api
from service.build_service import BuildService
from service.build_service import PlanService
from service.build_service import TestcaseService

build_ns = Namespace("build", description="构建记录管理")

build_service = BuildService()


@build_ns.route("")
class BuildController(Resource):
    build_get_parser = api.parser()
    build_get_parser.add_argument("id", type=int, location="args")

    @build_ns.expect(build_get_parser)
    def get(self):
        """
        构建记录的查找
        :return:
        """
        id = request.args.get("id")
        if id:
            data = build_service.get(id)
            if data:
                datas = [build_service.get(id).as_dict()]
                return {"code": 0, "msg": "data success get", "data": datas}
            else:
                return {"code": 40004, "msg": "data is not exists"}
        else:
            datas = [plan.as_dict() for plan in build_service.list()]
            return {"code": 0, "msg": "data success get", "data": datas}

    build_post_model = build_ns.model("build_post_model", {
        "plan_id": fields.Integer
    })

    @build_ns.expect(build_post_model)
    def post(self):
        """
        构建记录的新增
        :return:
        """
        plan_id = request.json.get("plan_id")
        build_id = build_service.save(plan_id)
        if build_id:
            return {"code": 0, "msg": f"{build_id} success add"}
        else:
            return {"code": 40001, "msg": "case is exists"}

    build_delete_parser = api.parser()
    build_delete_parser.add_argument("id", type=int, location="json", required=True)

    @build_ns.expect(build_delete_parser)
    def delete(self):
        """
        构建记录的删除
        :return:
        """
        plan_id = request.json.get("id")
        id = build_service.delete(plan_id)
        if id:
            return {"code": 0, "msg": f"{id} success delete"}
        else:
            return {"code": 40002, "msg": "case is not exists"}